package com.dshore.messagecenter.quartz.dataStat;

import java.util.ArrayList;
import java.util.List;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.dshore.messagecenter.dao.warning.ExceptionMessageDao;
import com.dshore.messagecenter.model.warning.MrExceptionMessage;

/**
 * 读取异常消息并入库
 * @author DSHORE
 *
 */
@Component
public class ExceptionMsgStat implements ApplicationRunner{

	@Autowired
	private AmqpTemplate amqpTemplate;
	
	@Autowired
	private ConnectionFactory connectionFactory;
	
	@Autowired
	private ExceptionMessageDao exceptionMessageDao;
	
	// 异常消息队列
	@Value("${rabbitmq.exception.queue}")
	private String exceptionQueue;
	
	@Override
	public void run(ApplicationArguments args) {
		RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
		// 启动后判断异常消息队列是否存在，不存在则新建
		if (rabbitAdmin.getQueueProperties(exceptionQueue) == null) {
			rabbitAdmin.declareQueue(new Queue(exceptionQueue));
		}
	}
	
	/**
	 * 接收异常消息
	 */
	public void receiveExceptionMsg() {
		// 异常消息集合
		List<MrExceptionMessage> exceptionMsgList = new ArrayList<MrExceptionMessage>();
		
		// 每次调用取500条消息
		for (int i = 0; i < 500; i++) {
			// 循环读取
			Object obj = amqpTemplate.receiveAndConvert(exceptionQueue);
			if (obj != null) {
				exceptionMsgList.add(JSON.parseObject(obj.toString().replace("appNo", "appCode")
						.replace("messageBody", "messageContentString"), MrExceptionMessage.class));
			} else {
				break;
			}
		}
		
		// 当集合中有数据时，进行保存
		if (exceptionMsgList.size() > 0) {
			exceptionMessageDao.addException(exceptionMsgList);
		}
	}
}
